﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using Crude.Common;
using Crude.Core;
using System.IO;

namespace Crude.Tasks
{
    public class GetCrudeReferences : Task
    {
        [Required]
        public ITaskItem[] References { get; set; }

        [Required]
        public string ProjectDirectory { get; set; }

        [Required]
        public string ProjectName { get; set; }

        [Output]
        public ITaskItem[] CrudeReferences { get; set; }

        public override bool Execute()
        {
            string pomFile = string.Format("{0}\\{1}.pom.xml", ProjectDirectory, ProjectName);            

            if (!File.Exists(pomFile))
            {
                Log.LogError("Pom file or project {0} is missing, please generate pom file {1}", ProjectName, pomFile);
                return false;
            }

            ProjectObjectModel mainPom = new ProjectObjectModelLoader(pomFile).Load();

            HashSet<string> crudeReferences = new HashSet<string>(
                from projectDependency in mainPom.Dependencies
                select projectDependency.Name);

            IList<ITaskItem> crudeReferencesList = new List<ITaskItem>();

            foreach (ITaskItem taskItem in References)
            {
                AssemblyName assemblyName = new AssemblyName(taskItem.ItemSpec);

                if (crudeReferences.Contains(assemblyName.Name))
                {
                    crudeReferencesList.Add(taskItem);
                }           
            }

            CrudeReferences = crudeReferencesList.ToArray();

            return true;
        }
    }
}
